import { InputNumberProps } from 'antd';
import { NumberPicker } from '@formily/antd';
interface NumberPProps extends InputNumberProps {
  editable?: boolean;
  unit?: string;
  unitInFront?: boolean;
  noFormat?: boolean;
}

function toFixed(number, precision) {
  var b = 1;
  if (isNaN(number)) return number;
  if (number < 0) b = -1;
  var multiplier = Math.pow(10, precision);
  return Math.round(Math.abs(number) * multiplier) / multiplier * b;
}

/**
 * 数值型组件
 * 增加了千分位的格式化
 * @param props
 */
export default (props: NumberPProps) => {
  const currencyFormatter = (value?: number | undefined | string) => {
    if (!value) return '';
    const { unit, precision } = props || {};
    if (precision || precision === 0) {
      return (toFixed(`${unit || ''} ${value}`,precision) + '').replace(/d{1,3}(?=(d{3})+(.d*)?$)/g, '$&,');
    }else{
      return `${unit || ''} ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    }
  };

  const currencyParser = (val: string | undefined) => {
    if (!val) return '';

    const { unit: currency } = props || {};

    const reg = currency ? new RegExp(`\\${currency}\\s?|(,*)`, 'g') : new RegExp(`,`, 'g');
    return val.replace(reg, '');
  };

  return props?.editable ? props?.noFormat ? (
    <NumberPicker
      formatter={(value?: number | undefined | string) => {
        if (props?.unitInFront) {
          return currencyFormatter(value);
        }

        if (!props?.unit) return `${value}`;
        if (!value) return '';

        return `${value}${props.unit}`;
      }}
      parser={(value: string | undefined) => {
        if (props?.unitInFront) {
          return currencyParser(value);
        }

        if (!value) return '';
        if (!props?.unit) return value;

        return value.replace(props.unit, '');
      }}
      {...props}
      defaultValue={undefined}
    />
  ) : (
    <NumberPicker
      formatter={(value) => {
        return currencyFormatter(value);
      }}
      parser={(value) => {
        return currencyParser(value);
      }}
      {...props}
      defaultValue={undefined}
    />
  ) : (
    currencyFormatter(props?.value)
  );
};
